// Local
#include "testferm.h"
#include "fermentable.h"
#include "weight.h"

// QtCore
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QString>

// QtXml
#include <QDomDocument>

// QtTest
#include <QTest>

// Standard libraries
#include <math.h>

// Entry point
QTEST_MAIN(testFerm)

void testFerm::Basics()
{
    QString Name = "Roasted Barley";
    int Version = 981729;
    FermentableType Type = FTGrain;
    Weight Amount(0.77,Kilogram);
    float Yield = 0.78;
    Color zeCol(800,EBC);
    Fermentable zeGrain(Name,Version,Type,Amount,Yield,zeCol);

    QVERIFY(zeGrain._Name==Name);
    QVERIFY(zeGrain._Version==Version);
    QVERIFY(zeGrain._Type==Type);
    QVERIFY(zeGrain._Amount==Amount);
    QVERIFY(zeGrain._Yield==Yield);
    QVERIFY(zeGrain._Color==zeCol);
}

#define EQUALVAL(a,b) QVERIFY(fabs(a-b)<0.000001)

void testFerm::ParseXML()
{
    Q_INIT_RESOURCE(test_ferm);

    // Parse XML
    QFile Input(":/caracrystal.xml");
    QDomDocument doc("caracrystal");
    QVERIFY(Input.open(QIODevice::ReadOnly));
    QVERIFY(doc.setContent(&Input));

    Fermentable zeGrain;
    QVERIFY(0==zeGrain.CreateFromXMLNode(doc));
    QVERIFY(zeGrain._Name=="Caramel/Crystal Malt - 20L");
    QVERIFY(zeGrain._Version==1);
    QVERIFY(zeGrain._Type==FTGrain);
    QVERIFY(zeGrain._Amount==Weight(0.453592,Kilogram));
    EQUALVAL(zeGrain._Yield,75.0);
    QVERIFY(zeGrain._Color==Color(20,SRM));
    QVERIFY(zeGrain._AddAfterBoil==false);
    QVERIFY(zeGrain._Origin=="US");
    QVERIFY(zeGrain._Notes=="Adds body, color and improves head retention.\nAlso called \"Crystal\" malt.");
    QVERIFY(zeGrain._CoarseFineDiff==1.5);
    EQUALVAL(zeGrain._Moisture,4.0);
    EQUALVAL(zeGrain._DiastaticPower,0.0);
    EQUALVAL(zeGrain._Protein,13.2);
    EQUALVAL(zeGrain._MaxInBatch,20.0);
    QVERIFY(zeGrain._RecommendMash==false);
    EQUALVAL(zeGrain._IBUGalPerLB,0);
}

void testFerm::ToXML()
{
    Fermentable zeGrain;
    zeGrain._Name = "Orge Grille 1000 EBC";
    zeGrain._Version = 4686;
    zeGrain._Type = FTGrain;
    zeGrain._Amount = Weight(770,Gram);
    zeGrain._Yield = 72.0;
    zeGrain._Color = Color(1000,EBC);
    zeGrain._AddAfterBoil = false;
    zeGrain._Origin = "Brouwland";
    zeGrain._Supplier = "Weyermann";
    zeGrain._CoarseFineDiff = 2.3;
    zeGrain._Moisture = 0.2;
    zeGrain._RecommendMash = true;
    zeGrain._MaxInBatch = 5.0;

    QString zeString;
    QTextStream Stream(&zeString);
    QDomDocument docWrite("beerxml");
    zeGrain.ToXMLNode(docWrite);
    docWrite.save(Stream,2);
    qDebug() << "Dumping generated XML" << endl << zeString;

    QDomDocument docRead("beerxml");
    QVERIFY(docRead.setContent(zeString));
    Fermentable parsedGrain;
    QVERIFY(0==parsedGrain.CreateFromXMLNode(docRead));
    QVERIFY(zeGrain==parsedGrain);
}
